package com.paradox.rpc.protocol.Netty;

import com.paradox.rpc.Carrier;
import com.paradox.rpc.Response;
import com.paradox.rpc.registry.Registry;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private Registry registry;

    public NettyServerHandler(Registry registry) {
        this.registry = registry;
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Carrier carrier= (Carrier) msg;
        Object impl=registry.pullService(carrier.getInterfaceName());
        Method method=impl.getClass().getMethod(carrier.getMethodName(),carrier.getArgTypes());
        Object res=method.invoke(impl,carrier.getArgs());
        Response response=new Response(carrier.getId(),res);
        ctx.channel().writeAndFlush(response);
    }
}
